package com.future.bantang.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;

import com.future.bantang.R;
import com.future.bantang.activity.BaseAllCommtsActivity;
import com.future.bantang.activity.RecommendShareActivity;
import com.future.bantang.adapter.RecommendHotAdapter;
import com.future.bantang.app.BanTangAPP;
import com.future.bantang.constants.BanTang;
import com.future.bantang.entity.RecommendHotDetailEntity;
import com.future.bantang.utils.JsonUtils;
import com.future.bantang.utils.NetUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.onekeyshare.OnekeyShare;

public class RecommendHotFragment extends BaseFragment implements AbsListView.OnScrollListener, RecommendHotAdapter.Callback {

    private static final String TAG = "RecommendHotFragment";
    //控件列表
    @ViewInject(R.id.lv_recommend_hot_show)
    private ListView lvRecommenedShow;

    //listview适配器
    private RecommendHotAdapter hotAdapter;

    //数据集合
    private List<RecommendHotDetailEntity.DataEntity.ListEntity> listEntities;

    //当前页码
    private int mPage = 0;

    //每页数据的数量
    private int pageSize = 10;

    //待获取数据数量
    private String elementId;

    //判断是否有两个界面
    private boolean isDoubleTag;

    // 双界面的第几条数据
    private int position;

    public RecommendHotFragment() {
    }

    public static RecommendHotFragment newInstance(String elementId, boolean isDoubleTag, int position) {
        RecommendHotFragment fragment = new RecommendHotFragment();
        Bundle args = new Bundle();
        args.putString("element_id", elementId);
        args.putBoolean("isDoubleTag", isDoubleTag);
        args.putInt("type_id", position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            elementId = getArguments().getString("element_id");
            isDoubleTag = getArguments().getBoolean("isDoubleTag");
            position = getArguments().getInt("type_id");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_recommend_hot, container, false);

        ViewUtils.inject(this, view);

        return view;
    }

    /**
     * 初始化
     *
     * @param view
     */
    @Override
    protected void initView(View view) {
        super.initView(view);

        listEntities = new ArrayList<>();

        hotAdapter = new RecommendHotAdapter(getActivity(), this);

        lvRecommenedShow.setAdapter(hotAdapter);

        lvRecommenedShow.setOnScrollListener(this);
    }

    /**
     * 加载数据
     */
    @Override
    protected void loadDatas() {
        NetUtils.RequestParamsBuilder builder = new NetUtils.RequestParamsBuilder();
        RequestParams params = null;
        if (isDoubleTag) {
            params = new NetUtils.RequestParamsBuilder()
                    .addPostParameter(BanTang.CLIENT_ID_KEY, BanTang.CLIENT_ID_VALUE)
                    .addPostParameter(BanTang.CLIENT_SECRET_KEY, BanTang.CLIENT_SECRET_VALUE)
                    .addPostParameter(BanTang.PAGE, mPage + "")
                    .addPostParameter(BanTang.PAGESIZE, pageSize + "")
                    .addPostParameter("type_id", position + "")
                    .addPostParameter("tag_id", elementId)
                    .build();
        } else {
            params = new NetUtils.RequestParamsBuilder()
                    .addPostParameter(BanTang.CLIENT_ID_KEY, BanTang.CLIENT_ID_VALUE)
                    .addPostParameter(BanTang.CLIENT_SECRET_KEY, BanTang.CLIENT_SECRET_VALUE)
                    .addPostParameter(BanTang.PAGE, mPage + "")
                    .addPostParameter(BanTang.PAGESIZE, pageSize + "")
                    .addPostParameter("element_id", elementId)
                    .build();
        }

        NetUtils.getSquareRecommenedHotDetail(isDoubleTag, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                RecommendHotDetailEntity hotDetailEntity = null;

                try {
                    hotDetailEntity = JsonUtils.perse(responseInfo.result, RecommendHotDetailEntity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                listEntities = hotDetailEntity.getData().getList();

                if (mPage == 0) {
                    hotAdapter.setDatas(listEntities);
                } else {
                    hotAdapter.addDatas(listEntities);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(getActivity(), "加载数据错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (lvRecommenedShow.getLastVisiblePosition() == listEntities.size() - 1) {
            mPage++;
            loadDatas();
        }
    }

    /**
     * 接口回调，把adapter数据回传,让fragment实现点击事件
     *
     * @param view
     */
    @Override
    public void onclick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_user_pic:
            case R.id.tv_user_name:
                String authorId = (String) view.getTag();
//                intent.setClass(getActivity(), );
                break;
            case R.id.ll_recommed_hot_share:
                String shareUrl = (String) view.getTag();
                intent.putExtra("shareUrl", shareUrl);
                intent.setClass(getActivity(), RecommendShareActivity.class);
                break;
            case R.id.iv_user_share:
                RecommendHotDetailEntity.DataEntity.ListEntity data = (RecommendHotDetailEntity.DataEntity.ListEntity) view.getTag();
                share(data);
                return;
            case R.id.tv_recommed_allcommts:
            case R.id.ll_recommed_hot_commts:
                List<RecommendHotDetailEntity.DataEntity.ListEntity.CommentsEntity> commentsList =
                        (List<RecommendHotDetailEntity.DataEntity.ListEntity.CommentsEntity>) view.getTag();
                intent.setClass(getActivity(), BaseAllCommtsActivity.class);
                intent.putExtra("commentsList", (Serializable) commentsList);
                break;
        }
        startActivity(intent);
    }

    private void share(RecommendHotDetailEntity.DataEntity.ListEntity data) {
        Log.d(TAG, "share() returned: " + data.toString());
        OnekeyShare oneKeyShare = BanTangAPP.getApp().getOneKeyShare();

        oneKeyShare.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        //  title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oneKeyShare.setTitle(data.getProduct().get(0).getTitle());
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oneKeyShare.setTitleUrl(data.getShare_url());
        // text是分享文本，所有平台都需要这个字段
        oneKeyShare.setText(data.getProduct().get(0).getTitle());
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oneKeyShare.setImageUrl(data.getShare_url());
        // url仅在微信（包括好友和朋友圈）中使用
        oneKeyShare.setUrl(data.getShare_url());
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oneKeyShare.setComment("说点什么...");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oneKeyShare.setSite("半糖精选");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oneKeyShare.setSiteUrl(data.getShare_url());

        // 启动分享GUI
        oneKeyShare.show(getActivity());
    }
}
